var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var vueRouter = require('./routes/vue');
var articleRouter = require('./routes/article');
var movieRouter = require('./routes/movie');
const formidableMiddleware = require('express-formidable');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(formidableMiddleware());
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'vueapp/dist')));

//设置跨域访问
app.disable('view cache');
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Cache-Control",'no-cache, no-store, must-revalidate');
  res.header("Pragma", "no-cache");
  res.header("Expires", 0);
  // res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/vueapp', vueRouter);
app.use('/article', articleRouter);
app.use('/movie', movieRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
let ws = require('ws');            //引入websocket模块
let socketServer = ws.Server;
let wss = new socketServer({port: 3001});
let clients = [];                //创建客户端列表，用于保存客户端及相关连接信息
wss.on('connection', ws => {
  ws.send(JSON.stringify({
    type: 'get_ident'
  }));
  ws.on('message', msg_str => {
    let msg = JSON.parse(msg_str);
    switch(msg.type){
      case 'get_ident':
        clients.push({
          nick_name: msg.user_name,
          user_id: msg.user_id,
          ws,
        });
        break;
      case 'broadcast':
        braodcast(msg);
        break;
    }
    console.log(msg);
  });
  ws.on('close', msg => {
    console.log(msg);
  });
  function braodcast(msg){
    clients.forEach(item=>{
      item.ws.send(JSON.stringify({
        type: 'broadcast',
        user_id: msg.user_id,
        nick_name: msg.nick_name,
        content: msg.content,
      }));
    })
  }
});
module.exports = app;
